package com.suli.interceptor;

import com.scenic.util.JWTUtils;
import com.scenic.util.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 * @version 1.0 <br/>
 * <p style="font-family:SimSun;font-weight:bold">时间:<br/>2022/3/16 9:57</p>
 */
@Component
@Slf4j
public class WebAppInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("scenic-token");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        if(!ObjectUtils.isEmpty(token)){
            if(JWTUtils.checkFormat(token)) {
               if(JWTUtils.checkToken(token)){
                   return true;
               }else {
                   log.info("请求已被拦截");
                   //如果token过期
                  getResponse(2009, response,"token已过期");
                   return false;
               }
            }else {
                //如果token格式错误
                getResponse(2008, response,"token格式错误");
                log.info("请求已被拦截");
                return false;
            }
        }
        log.info("请求已被拦截");
        //token不存在
        getResponse(2007, response,"token不存在");
            return false;
    }
    private void getResponse(Integer code,HttpServletResponse response,String message) {
        try {
            String messageBad = new ObjectMapper().writeValueAsString(ResponseResult.error().code(code).message(message));
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(messageBad);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
